package org.wmq.commonservice.interceptor;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.wmq.commonutil.constant.RedisConstant;
import org.wmq.commonutil.context.SystemUserHolder;
import org.wmq.commonutil.result.Result;
import org.wmq.shopmodel.Entity.system.SystemUser;

@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")){
            return true;
        }
        String token = request.getHeader("token");
        if (token == null){
            response.getWriter().write(JSON.toJSONString(Result.error("token不能为空")));
            return false;
        }
        String systemUserJson = this.redisTemplate.opsForValue().get(RedisConstant.LOGIN_USER_INFO_CACHE_PREFIX + token);
        if (systemUserJson == null){
            response.getWriter().write(JSON.toJSONString(Result.error("token错误或token已过期")));
            return false;
        }
        this.redisTemplate.expire(RedisConstant.LOGIN_USER_INFO_CACHE_PREFIX + token, RedisConstant.LOGIN_USER_INFO_EXPIRE_MS, java.util.concurrent.TimeUnit.MILLISECONDS);
        SystemUserHolder.set(JSON.parseObject(systemUserJson, SystemUser.class));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SystemUserHolder.remove();
    }
}
